package linkedlist;

/**
 * @author tong
 * @date 2022/1/6 16:47
 */
public class DoubleLinkedList {
    private DoubleNode<Person> head = new DoubleNode<>(new Person());

    public void list() {
        if (head.next == null) {
            System.out.println("empty");
            return;
        }
        DoubleNode<Person> temp = head;
        while (true) {
            if (temp == null) {
                break;
            }
            System.out.println(temp.data);
            temp = temp.next;
        }
    }

    public void add(DoubleNode<Person> node) {
        DoubleNode<Person> temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = node;
        node.pre = temp;
    }

    public void update(DoubleNode<Person> node) {
        if (head.next == null) {
            System.out.println("empty");
            return;
        }
        DoubleNode<Person> temp = head;
        while (true) {
            if (temp == null) {
                System.out.println("not exist");
                return;
            }
            if (temp.data.getNo() == node.data.getNo()) {
                break;
            }
            temp = temp.next;
        }
        temp.data.setName(node.data.getName());
    }

    /**
     * 可以自我删除，不需要找前一个节点
     *
     * @param no
     */
    public void delete(int no) {
        // 双链表可以直接从下一个节点开始找
        DoubleNode<Person> temp = head.next;
        while (true) {
            if (temp.data.getNo() == no) {
                break;
            }
            if (temp.next == null) {
                System.out.println("not found");
                return;
            }
            temp = temp.next;
        }
        temp.pre.next = temp.next;
        if (temp.next != null) {
            temp.next.pre = temp.pre;
        }
    }

    public void insert(DoubleNode<Person> node) {
        DoubleNode<Person> temp = head;
        while (true) {
            if (temp.next == null || temp.next.data.getNo() > node.data.getNo()) {
                break;
                //和下一个节点比较
            }
            if (temp.next.data.getNo() == node.data.getNo()) {
                System.out.println(temp.data.getNo() + "exist!");
                return;
            }

            temp = temp.next;
        }
        // 插入temp的后一个位置
        if (temp.next != null) {
            temp.next.pre = node;
            node.next = temp.next;
        }
        temp.next = node;
        node.pre = temp;

    }


    public static void main(String[] args) {
        DoubleLinkedList list = new DoubleLinkedList();

        DoubleNode<Person> node1 = new DoubleNode<>(new Person(1, "a"));
        DoubleNode<Person> node3 = new DoubleNode<>(new Person(3, "c"));
        DoubleNode<Person> node5 = new DoubleNode<>(new Person(5, "e"));
        list.insert(node5);
        list.insert(node1);
        list.insert(node3);

        list.list();

    }
}
